package com.lcj.nebula.task;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.lcj.common.exception.AochException;
import com.lcj.nebula.db.dao.OrderMonitoringDao;
import com.lcj.nebula.db.dao.OrderVoiceTextDao;
import com.lcj.nebula.db.pojo.OrderMonitoringEntity;
import com.lcj.nebula.util.SensitiveWordUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ciModel.auditing.AuditingJobsDetail;
import com.qcloud.cos.model.ciModel.auditing.SectionInfo;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingResponse;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Component
@Slf4j
public class VoiceTextCheckTask {
    @Value("${tencent.cloud.appId}")
    private String appId;

    @Value("${tencent.cloud.secretId}")
    private String secretId;

    @Value("${tencent.cloud.secretKey}")
    private String secretKey;

    @Value("${tencent.cloud.bucket-public}")
    private String bucketPublic;

    @Resource
    private OrderVoiceTextDao orderVoiceTextDao;

    @Resource
    private OrderMonitoringDao orderMonitoringDao;

    @Resource
    private SensitiveWordUtil sensitiveWordUtil;

    /**
     * AI分析分本，更新Hbase数据记录
     * @param orderId
     * @param content
     * @param uuid
     */
    @Async
    @Transactional
    public void checkText(long orderId, String content, String uuid) {

        String label = "正常"; //审核结果
        String suggestion = "Pass"; //后续建议
        if (StrUtil.isNotBlank(content)) {
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region("ap-beijing");
            ClientConfig clientConfig = new ClientConfig(region);
            COSClient client = new COSClient(cred, clientConfig);
            //创建任务请求对象
            TextAuditingRequest request = new TextAuditingRequest();
            request.setBucketName(bucketPublic);
            //设置内容，文本内容的Base64编码
            String base64Str = Base64.getEncoder().encodeToString(content.getBytes());
            request.getInput().setContent(base64Str);
            //设置审核类型参数
            request.getConf().setDetectType("all");
            //调用接口,获取任务响应对象
            TextAuditingResponse response = client.createAuditingTextJobs(request);
            AuditingJobsDetail detail = response.getJobsDetail();

            String state = detail.getState();
            ArrayList keywords = new ArrayList();
            if ("Success".equals(state)) {
                //检测结果
                HashMap<String, String> detailMap = new HashMap<>();
                detailMap.put("Porn", "涉黄");
                detailMap.put("Ads", "广告");
                detailMap.put("Illegal", "广告");
                detailMap.put("Abuse", "谩骂");
                detailMap.put("Politics", "政治");
                detailMap.put("Terrorism", "恐怖主义");
                detailMap.put("Sensitive", "敏感");
                detailMap.put("Violation", "违规");
                label = detailMap.get(detail.getLabel());

                HashMap<String, String> template = new HashMap();
                template.put("0", "通过");
                template.put("1", "拦截");
                template.put("2", "人工审核");
                //后续建议
                String result = detail.getResult();
                suggestion = template.get(result);
                //违规关键词
                List<SectionInfo> list = detail.getSectionList();
                for (SectionInfo info : list) {
                    String keywords_1 = info.getPornInfo().getKeywords();
                    String keywords_2 = info.getIllegalInfo().getKeywords();
                    String keywords_3 = info.getAbuseInfo().getKeywords();
                    if (keywords_1.length() > 0) {
                        List temp = Arrays.asList(keywords_1.split(","));
                        keywords.addAll(temp);
                    }
                    if (keywords_2.length() > 0) {
                        List temp = Arrays.asList(keywords_2.split(","));
                        keywords.addAll(temp);
                    }
                    if (keywords_3.length() > 0) {
                        List temp = Arrays.asList(keywords_3.split(","));
                        keywords.addAll(temp);
                    }
                    log.info("腾讯数据万象检测结果:", keywords_1 + "," + keywords_2 + "," +keywords_3);
                }
            }
            Long id = orderVoiceTextDao.searchIdByUuid(uuid);
            if (id == null) {
                throw new AochException("没有找到行程语音文本记录");
            }

            //ToolGood自定义敏感词检测
            List<String> sensitiveWord = sensitiveWordUtil.findSensitive(content);
            keywords.addAll(sensitiveWord);
            if(!sensitiveWord.isEmpty()) {
                label = "危险";
                suggestion = "Block";

            }

            HashMap param = new HashMap();
            param.put("id", id);
            param.put("label", label);
            param.put("suggestion", suggestion);
            param.put("keywords", ArrayUtil.join(keywords.toArray(), ","));
            
            //更新数据表中该文本的审核结果
            int rows = orderVoiceTextDao.updateCheckResult(param);
            if (rows != 1) {
                throw new AochException("更新内容检查结果失败");
            }
            log.debug("更新内容验证成功");
            
            //查询该订单有多少个录音文本和需要人工审核的文本
            HashMap map = orderMonitoringDao.searchOrderRecordsAndReviews(orderId);
            
            id = MapUtil.getLong(map, "id");
            Integer records = MapUtil.getInt(map, "records");
            Integer reviews = MapUtil.getInt(map, "reviews");
            OrderMonitoringEntity entity = new OrderMonitoringEntity();
            entity.setId(id);
            entity.setOrderId(orderId);
            entity.setRecords(records + 1);
            if (suggestion.equals("Review")) {
                entity.setReviews(reviews + 1);
            }
            if (suggestion.equals("Block")) {
                entity.setSafety("danger");
            }
            
            //更新order_monitoring表中的记录
            orderMonitoringDao.updateOrderMonitoring(entity);

        }
    }
}
